# -*- coding:utf-8 -*-
'''
author:***y
time:2019-08-28
主要功能说明：
1、获取登录接口的token
2、介入闲聊和qa问答，批量测试闲聊和qa模型，得出模型的正确率；
这里优化了一下比较方法，比较qa和闲聊的得分和设定的值对比，小于设定的值，则返回固定句式，
否则那个值大，则返回哪个的结果。
'''
import requests
import csv
import pandas as pd
import json


class TestAi():
    def __init__(self):
        # 初始化登录接口
        # login_url = 'https://api.icarbonx.com/oauth2/token?grant_type=password&sms_verify=true'
        # login_header = {"Authorization": "Basic Y29tLm1ldW0uY29hY2guaXBob25lOjdmYTYyZmFmYzgxZTgwMzY="}
        # login_data = {
        #     "username": "15012345678",
        #     "password": "888888",
        #     "appName": "health-buddy",
        #     "grant_type": "password",
        #     "sms_verify": "true"
        # }
        # # 登录请求接口
        # r_login = requests.post(url=login_url, data=login_data, headers=login_header)
        print("ok")

    def login_token(self):

        # 初始化登录接口
        login_url = 'https://api.icarbonx.com/oauth2/token?grant_type=password&sms_verify=true'
        login_header = {"Authorization": "Basic Y29tLm1ldW0uY29hY2guaXBob25lOjdmYTYyZmFmYzgxZTgwMzY="}
        login_data = {
            "username": "15012345678",
            "password": "888888",
            "appName": "health-buddy",
            "grant_type": "password",
            "sms_verify": "true"
        }
        # 登录请求接口
        r_login = requests.post(url=login_url, data=login_data, headers=login_header)
        # # 获取登录的响应报文
        # print(r_login.text)
        # login_response = json.loads(r_login.text)
        # # 保存登录的token信息
        # access_token = login_response['access_token']
        token = r_login.json()['access_token']
        print(token)
        '''请求接口获取token值'''
        return token

    def qa_chat(self):

        # 初始化回复失败的变量
        qa_flag_init = 0  # qa模型匹配成功值的初始化
        chat_flag_init = 0  # 闲聊模型匹配值的初始化
        end_flag_init = 0  # 结束对话模型匹配值的初始化
        # 初始化模型阀值
        qa_threshold_init = '0.8'
        # 碳小云学习标准回复
        qa_study_answer = '我正在学习中'

        # 读取csv文件
        with open('E:\\test\\HB\\pyqa.csv', 'r') as csvFile:
            reader = csv.reader(csvFile)
            print(type(reader))
            next(reader)
            for row in reader:
                print(row)
                print(type(row))
                print(row[1])
                print(type(row[1]))

                # 食物qa问答接口的请求参数msg
                qa_msg = {"msg": row[1]}
                print(qa_msg)
                # 获取登录的token
                qa_headers = {"Authorization": "Bearer " + self.login_token()}
                # qa问答的url
                qa_url = 'https://api.icarbonx.com/chatbot/qa'
                # qa问答模型接口请求
                r_qa = requests.post(url=qa_url, data=qa_msg, headers=qa_headers)
                # 获取响应报文
                print(r_qa.text)
                # 转换响应结果为dict格式
                qa_response = json.loads(r_qa.text)
                print(qa_response)
                print(type(qa_response))

                # 判断响应结果是否为空,不为空，则获取answer和score的值
                if qa_response:
                    print(qa_response[0])
                    qa_response_all = qa_response[0]
                    # 获取answer的值
                    qa_response_answer = qa_response_all['answer']
                    qa_response_score = qa_response_all['score']
                    print("qa的answer：" + qa_response_answer)
                else:
                    qa_flag_init = qa_flag_init + 1
                    print("qa问答失败%d" % qa_flag_init)

                # chat闲聊模型请求，闲聊的url
                chit_url = 'https://api.icarbonx.com/chit/st'
                # 闲聊的接口请求
                r_chit = requests.post(url=chit_url, data=qa_msg, headers=qa_headers)
                # 获取响应报文
                print(r_chit.text)
                # 转换响应结果为dict
                chit_response = json.loads(r_chit.text)
                print(chit_response)
                print(type(chit_response))

                # 判断响应结果是否为空，不为空，则获取answer和score的值
                if chit_response:
                    print(chit_response[0])
                    chit_response_all = chit_response[0]
                    # 获取answer和score的值
                    chit_response_answer = chit_response_all['answer']
                    chit_response_score = chit_response_all['score']
                    print("chit的answer" + chit_response_answer)
                else:
                    qa_error_init = qa_error_init + 1
                    print("闲聊失败%d" % qa_error_init)
                    print("先睡了")

                '''比较qa和闲聊的得分和设定的值对比，小于设定的值，
                则返回固定句式，否则那个值大，则返回哪个的结果'''

                data_row = ['question', 'answer']
                if qa_response_score > chit_response_score:

                    if chit_response_score > qa_threshold_init:
                        print("---------匹配qa模型成功---------")
                        qa_flag_init = qa_flag_init + 1
                        print("匹配qa模型成功：%d" % qa_flag_init)
                        # 赋值qa_msg_answer 为qa的答案
                        qa_msg_answer = qa_response_answer
                    else:
                        if qa_response_score > qa_threshold_init:
                            print("---------匹配qa模型成功---------")
                            qa_flag_init = qa_flag_init + 1
                            print("匹配qa模型成功：%d" % qa_flag_init)
                            # 赋值qa_msg_answer 为qa的答案
                            qa_msg_answer = qa_response_answer

                        else:
                            print("-----结束场景，碳小云回去学习中---")
                            end_flag_init = end_flag_init + 1
                            print("碳小云回去充电次数：%d" % end_flag_init)
                            # 赋值qa_msg_answer 为碳小云的学习的答案
                            qa_msg_answer = qa_study_answer

                elif qa_response_score < chit_response_score:

                    if chit_response_score < qa_threshold_init:
                        print("-----结束场景，碳小云回去学习中---")
                        end_flag_init = end_flag_init + 1
                        print("碳小云回去充电次数：%d" % end_flag_init)
                        # 赋值qa_msg_answer 为碳小云的学习的答案
                        qa_msg_answer = qa_study_answer
                    else:
                        if qa_threshold_init > qa_response_score:
                            print("---------匹配闲聊模型成功---------")
                            chat_flag_init = chat_flag_init + 1
                            print("匹配闲聊模型成功：%d" % chat_flag_init)
                            # 赋值qa_msg_answer 为闲聊的答案
                            qa_msg_answer = chit_response_answer

                        else:
                            print("---------匹配闲聊模型成功---------")
                            chat_flag_init = chat_flag_init + 1
                            print("匹配闲聊模型成功：%d" % chat_flag_init)
                            # 赋值qa_msg_answer 为闲聊的答案
                            qa_msg_answer = chit_response_answer

                # qa_msg_answer = qa_response_answer
                #     # # 保存qa的answer到本地文件as
                #     # with open('E:\\test\\HB\\answer.csv','a',encoding='utf-8-sig') as f:
                #     #     csv_write = csv.writer(f)
                #     #     data_row[1] = qa_msg_answer
                #     #     data_row[0] = row[1]
                #     #
                #     #     print(type(data_row))
                #     #     csv_write.writerow(data_row)
                #     #     print("qa的回答")
                #     #     f.close()
                # else:
                #     qa_msg_answer = chit_response_answer

                # 如果返回结果中存在\n换行符，则替换成为分号；
                if '\n' in qa_msg_answer:
                    qa_msg_answer = qa_msg_answer.replace("\n", ";")

                # 去掉回答结果中的逗号
                qa_msg_answer = qa_msg_answer.replace(",", "")

                # 保存chit的answer到本地文件
                with open('E:\\test\\HB\\answer.csv', 'a', encoding='utf-8-sig') as f:
                    # csv_write = csv.writer(f)
                    data_row[0] = row[1]
                    data_row[1] = qa_msg_answer

                    # data_row = list(data_row)
                    # print(data_row)
                    f.write(','.join(data_row))
                    f.write("\n")
                    # f.write("\\n")

                    f.close()

        # 关闭csv
        csvFile.close()

        print("------模型结果统计------")
        print("匹配闲聊模型成功：%d" % chat_flag_init)

        print("碳小云回去充电次数：%d" % end_flag_init)
        print("匹配qa模型成功：%d" % qa_flag_init)


if __name__ == '__main__':
    qc = TestAi()
    qc.qa_chat()
